package redis

import (
	"context"
	"fmt"
	"time"

	"github.com/go-redis/redis/v8"

	"gin-scaffold/setting"
)

var rdb *redis.Client

func Init() (err error) {
	rdb = redis.NewClient(&redis.Options{
		Addr:         fmt.Sprintf("%s:%d", setting.Conf.RedisConfig.Host, setting.Conf.RedisConfig.Port),
		Password:     setting.Conf.RedisConfig.Password,     // no password set
		DB:           setting.Conf.RedisConfig.DB,           // use default DB
		PoolSize:     setting.Conf.RedisConfig.PoolSize,     // 连接池大小
		MinIdleConns: setting.Conf.RedisConfig.MinIdleConns, // 最小空闲连接数
	})

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	_, err = rdb.Ping(ctx).Result()
	return err
}
